package com.zhou.base.components.feign.simple.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TestGuavaCacheUtil {

	private static Cache<String, Object> cache;
	static {
		cache = CacheBuilder.newBuilder().maximumSize(10000)
				.initialCapacity(10)
				.concurrencyLevel(8)
				.expireAfterAccess(10, TimeUnit.MINUTES)
				.removalListener(rn -> {
					if (log.isInfoEnabled()) {
						log.info("被移除缓存{}:{}", rn.getKey(), rn.getValue());
					}
				}).build();
	}

	/**
	 * @desction: 获取缓存
	 */
	public static Object get(String key, Callable callable)  {
		Object o = null;
		try {
			o = cache.get(key, callable);
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}
		return o;
	}

	/**
	 * @desction: 放入缓存
	 */
	public static void put(String key, Object value) {
		if (StringUtils.isNotEmpty(key) && value != null) {
			cache.put(key, value);
		}
	}

	/**
	 * @desction: 移除缓存
	 */
	public static void remove(String key) {
		if (StringUtils.isNotEmpty(key)) {
			cache.invalidate(key);
		}
	}

	/**
	 * @desction: 批量删除缓存
	 */
	public static void remove(List<String> keys) {
		if (keys != null && keys.size() > 0) {
			cache.invalidateAll(keys);
		}
	}
}
